package com.example.vueserver.vueserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.vueserver.vueserver.bean.SysRole;
import com.example.vueserver.vueserver.bean.SysUser;
import com.example.vueserver.vueserver.service.SysUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/usermanage")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @RequestMapping("/list")
    public List<SysUser> userList(){
        System.out.println("获取用户列表");
        return sysUserService.list();
    }

    @RequestMapping("/listPage")
    public PageInfo<SysUser> listPage(@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "1") int pageSize) {
        System.out.println("获取用户分页列表");
        System.out.println(pageIndex+"************"+pageSize);
        return sysUserService.listPage(pageIndex, pageSize);
    }
    @RequestMapping("/listSearchPage")
    public PageInfo<SysUser> listSearchPage(@RequestBody String conditions){
        JSONObject jsonObject = JSON.parseObject(conditions);

        return null;
    }

    @RequestMapping("/saveUser")
    public Map<String,Object> saveOrUpdateUser(@RequestBody String object){
        //处理json中角色列表无法直接转换成SysUser对象中的List<SysRole>
        JSONArray roles = (JSONArray) JSON.parseObject(object).get("roleList");
        List<SysRole> roleList = new ArrayList<>();
        for(Object roleid:roles){
            SysRole role = new SysRole();
            role.setId((Integer) roleid);
            roleList.add(role);
        }
        SysUser user = JSON.parseObject(object, SysUser.class);
        user.setRoles(roleList);
        Map map = this.sysUserService.saveOrUpdate(user);
        Map resultMap = new HashMap();
        resultMap.putAll(map);
        return resultMap;
    }
}
